/*
 * @Author: byron
 * @Date: 2022-01-25 10:45:48
 * @LastEditTime: 2022-01-29 19:50:28
 */

import {
    getDiary
} from '@/api/index'
import {
    formatTime
} from '@/utils/time'


const state = {
    diaryNum: sessionStorage.getItem('DIARY_NUM') != null ?
        sessionStorage.getItem('DIARY_NUM') : 0,
    diaryList: sessionStorage.getItem('DIARY_LIST') != null ?
        JSON.parse(sessionStorage.getItem('DIARY_LIST')) : [],
}

// 同步方法
const mutations = {
    SET_DIARY_NUM(state, diaryNum) {
        if (diaryNum) {
            state.diaryNum = diaryNum
            sessionStorage.setItem('DIARY_NUM', diaryNum)
        } else {
            state.diaryNum = 0
            sessionStorage.removeItem('DIARY_NUM')
        }
    },
    SET_DIARY_LIST(state, diaryList) {
        if (diaryList.length != 0) {
            state.diaryList = diaryList
            sessionStorage.setItem('DIARY_LIST', JSON.stringify(diaryList))
        } else {
            state.diaryList = []
            sessionStorage.removeItem('DIARY_LIST')
        }
    },
}

// 异步方法
const actions = {
    async agetDiary({
        commit
    }) {
        try {
            const response = await getDiary()
            const {
                code,
                data,
                msg
            } = response
            if (code === 200) {
                const total = data.length
                const result = data.map((item) => {
                    item.time = formatTime(item.time)
                    return item
                })
                commit('SET_DIARY_NUM', total)
                commit('SET_DIARY_LIST', result)
                return Promise.resolve()
            } else {
                return Promise.reject(msg)
            }
        } catch (e) {
            console.log(e)
        }
    },
}

export default {
    namespaced: true,
    mutations,
    actions,
    state,
}